//
//  YHGameLayerFight.cpp
//  ThunderWarriors
//
//  Created by mac on 13-6-22.
//
//

#include "YHGameLayerFight.h"
#include "YHGameLayerMap.h"
#include "YHGameDefine.h"
#include "YHBullet.h"
#include "YHEnemyShip.h"

IMPLEMENT_CREATE_CLASS(YHGameLayerFight);


static YHGameLayerFight* _pYHGameLayerFightInstance = NULL;

YHGameLayerFight* YHGameLayerFight::sharedGameLayerFight(){
    if (_pYHGameLayerFightInstance == NULL) {
        _pYHGameLayerFightInstance = YHGameLayerFight::create();
    }
    return  _pYHGameLayerFightInstance;
}

YHGameLayerFight::YHGameLayerFight()
{
    m_ship = NULL;
    m_spriteCloudsFar = NULL;
    m_spriteCloudsNear = NULL;
    m_shipBullets = NULL;
    m_enemyShips = NULL;
    m_enemyBullets = NULL;
    m_shipBullets = NULL;
}

YHGameLayerFight::~ YHGameLayerFight()
{
    m_enemyShips->removeAllObjects();
    m_enemyShips->release();
 
}

bool YHGameLayerFight::init()
{
    m_winSize = CCDirector::sharedDirector()->getWinSize();
    m_winRect = CCRect(0, 0, m_winSize.width, m_winSize.height);
    //加载背景
    YHGameLayerMap* mapBg = YHGameLayerMap::create();
    this->addChild(mapBg, kMapZorder);
    
    
    //加载云层
    loadClouds();
    
    //初始化敌机子弹数组
    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(s_bullet_plist);
    CCSpriteFrame* spriteFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(s_play_bullet);
    m_enemyBullets = CCSpriteBatchNode::createWithTexture(spriteFrame->getTexture());
    m_enemyBullets->ignoreAnchorPointForPosition(false);
    m_enemyBullets->setAnchorPoint(ccp(0,0));
    m_enemyBullets->setPosition(ccp(0,0));
    ccBlendFunc cbl = {GL_SRC_ALPHA, GL_ONE};
    m_enemyBullets->setBlendFunc(cbl);
    this->addChild(m_enemyBullets, kEnemyShipBulletZorder);
    //初始化飞船子弹数组
    m_shipBullets = CCSpriteBatchNode::createWithTexture(spriteFrame->getTexture());
    m_shipBullets->ignoreAnchorPointForPosition(false);
    m_shipBullets->setAnchorPoint(ccp(0,0));
    m_shipBullets->setPosition(ccp(0,0));
    ccBlendFunc cbl2 = {GL_SRC_ALPHA, GL_ONE};
    m_shipBullets->setBlendFunc(cbl2);
    this->addChild(m_shipBullets, kShipBulleZorder);
    
    //加载飞船
    m_ship = YHShip::create();
    this->addChild(m_ship, kShipZorder);
    m_ship->setPosition(ccp(m_winSize.width/2, m_ship->getContentSize().height/2 + 30));
    
    
    //加载敌机
    m_enemyShips = CCArray::create();
    m_enemyShips->retain();
    
    for (int i = 0; i < 3; i ++) {
        time(NULL);
        YHEnemyShip* enemyShip = YHEnemyShip::createWithEnemyType(YHEnemyTypes[i]);
        enemyShip->setPosition(CCPoint(i*50+ rand()%150, 100+rand()%200+i*100));
        this->addChild(enemyShip, kShipZorder);
        
        m_enemyShips->addObject(enemyShip);
    }
    
    this->scheduleUpdate();
    
    
    this->setTouchEnabled(true);
    return true;
}

bool YHGameLayerFight::loadClouds()
{
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    m_spriteCloudsNear = CCSpriteBatchNode::create(s_cloud1);
    m_spriteCloudsNear->setPosition(ccp(0, 0));
    
    m_spriteCloudsFar = CCSpriteBatchNode::create(s_cloud2);
    m_spriteCloudsFar->setPosition(ccp(0, 0));
    
    
    this->addChild(m_spriteCloudsNear, kCloudNearZorder);
    this->addChild(m_spriteCloudsFar, kCloudFarZorder);
    
    this->schedule(schedule_selector(YHGameLayerFight::generateRandomClouds), 2);
    return true;
}

void YHGameLayerFight::generateRandomClouds(float t)
{
    //定义简单的云层加入，分两层，近层云离视线近，速度快，云层大。远层云离视线远，速度慢，云层小
    time(NULL);
    
    //加远层云
    int s = rand()%4;
    for (int t = 0; t < s; t ++) {
        CCSprite* cloudFar = CCSprite::createWithTexture(m_spriteCloudsFar->getTexture());
        cloudFar->ignoreAnchorPointForPosition(false);
        cloudFar->setAnchorPoint(ccp(0, 0));
        cloudFar->setScale(1.0f);
        int posX = rand()%220;
        int offset = t * 60;
        offset = (offset==0? 60 : offset);
        int offsetY = rand()%offset;
        int posY = 480 + offsetY;
        cloudFar->setPosition(ccp(posX, posY));
        m_spriteCloudsFar->addChild(cloudFar);
        
        float duration = (posY + 70 )/50 ;
        CCMoveBy* moveBy = CCMoveBy::create(duration, ccp(0,-70-posY));
        CCCallFuncN* callfuncN_cloud_near = CCCallFuncN::create(this, callfuncN_selector(YHGameLayerFight::removeCloud));
        CCFiniteTimeAction* sequence = CCSequence::create(moveBy, callfuncN_cloud_near, NULL);
        cloudFar->runAction(sequence);
    }
    
    //加近层云
    
    int i = rand()%3;
    for (int j = 0; j < i; j++) {
        CCSprite* cloudNear = CCSprite::createWithTexture(m_spriteCloudsNear->getTexture());
        cloudNear->ignoreAnchorPointForPosition(false);
        cloudNear->setAnchorPoint(ccp(0, 0));
        cloudNear->setScale(1.7f);
        int posX = rand()%220;
        int offset = j * 130;
        offset = (offset==0? 130 : offset);
        int offsetY = rand()%offset;
        int posY = 480 + offsetY;
        cloudNear->setPosition(ccp(posX, posY));
        m_spriteCloudsNear->addChild(cloudNear);
        
        float duration = (posY + 70 )/100 ;
        CCMoveBy* moveBy = CCMoveBy::create(duration, ccp(0,-120-posY));
        CCCallFuncN* callfuncN_cloud_near = CCCallFuncN::create(this, callfuncN_selector(YHGameLayerFight::removeCloud));
        CCFiniteTimeAction* sequence = CCSequence::create(moveBy, callfuncN_cloud_near, NULL);
        cloudNear->runAction(sequence);
    }
    
    
}

void YHGameLayerFight::removeCloud(CCNode* nodeCloud)
{
    CCSprite* sprite = (CCSprite*)nodeCloud;
    if (sprite->getParent()) {
        sprite->removeFromParentAndCleanup(true);
    }
}

void YHGameLayerFight::update(float dt)
{
    if (m_shipBullets) {
        CCArray* bulletsArray =  m_shipBullets->getChildren();
        CCObject* bullet = NULL;
        CCARRAY_FOREACH(bulletsArray, bullet){
            bullet->update(dt);
        }
    }
    
     
    CCArray* enemyBullets = m_enemyBullets->getChildren();
    CCObject* bullet = NULL;
    CCARRAY_FOREACH(enemyBullets, bullet){
        bullet->update(dt);
    }
    //检查碰撞
    checkCollide();
    //移除
    removeInactiveSprite();
   
}

void YHGameLayerFight::checkCollide(){
    
    //检查飞船子弹和敌机的碰撞
    if (m_shipBullets && m_enemyShips->count() > 0) {
        CCArray* bulletsArray =  m_shipBullets->getChildren();
        CCObject* bullet = NULL;
        CCARRAY_FOREACH(bulletsArray, bullet){ //遍历子弹
            YHBullet* bulletSprite = (YHBullet*)bullet;
            CCObject* enemy = NULL;
            CCARRAY_FOREACH(m_enemyShips, enemy){ //遍历敌机
                YHEnemyShip* enemyShip = (YHEnemyShip*) enemy;
                if (bulletSprite->getCollideCrect().intersectsRect(enemyShip->getCollideCrect())) {
                    bulletSprite->hurt();
                    enemyShip->hurt();
                }
            }
        }
    }
    
    //检查敌机子弹和飞船的碰撞
    if (m_ship && m_enemyBullets->getChildren()->count()>0) {
        CCArray* bulletsArray =  m_enemyBullets->getChildren();
        CCObject* bullet = NULL;
        CCARRAY_FOREACH(bulletsArray, bullet){ //遍历敌机子弹
            YHBullet* bulletSprite = (YHBullet*)bullet;
            if (bulletSprite->getCollideCrect().intersectsRect(m_ship->getCollideCrect())) {
                bulletSprite->hurt();
                m_ship->hurt();
            }
        }
    }
    
    //检查敌机和飞船的碰撞
    if (m_enemyShips->count() > 0 && m_ship) {
        CCObject* enemy = NULL;
        CCARRAY_FOREACH(m_enemyShips, enemy){ //遍历敌机
            YHEnemyShip* enemyShip = (YHEnemyShip*) enemy;
            if (enemyShip->getCollideCrect().intersectsRect(m_ship->getCollideCrect())) {
                enemyShip->hurt();
                m_ship->hurt();
            }
        }
    }

}

void YHGameLayerFight::removeInactiveSprite(){
    if (m_shipBullets) {
        CCArray* bulletsArray =  m_shipBullets->getChildren();
        CCObject* bullet = NULL;
        CCARRAY_FOREACH(bulletsArray, bullet){
            YHBullet* bulletSprite = (YHBullet*)bullet;
            if (! bulletSprite->getIsActive()) { //检查子弹是否活动
                bulletSprite->destroy();
            }
            else { //检查是否超出屏幕边界
                bool isCollide = bulletSprite->getCollideCrect().intersectsRect(m_winRect);
                if (!isCollide) {
                    bulletSprite->removeFromParentAndCleanup(true);
                }
            }
        }
    }
    
    if (m_enemyShips &&  m_enemyShips->count() > 0) {
        CCObject* enemy = NULL;
        CCARRAY_FOREACH(m_enemyShips, enemy){
            YHEnemyShip* enemyShip = (YHEnemyShip*) enemy;
            if (!enemyShip->getIsActive()) { //检查敌机是否活动
                m_enemyShips->removeObject(enemyShip);
                enemyShip->destroy();
            }
        }
    }

    CCArray* enemyBullets = m_enemyBullets->getChildren();
    CCObject* bullet = NULL;
    CCARRAY_FOREACH(enemyBullets, bullet){ //检查敌机的子弹是否活动和超出边界
        YHBullet* bulletSprite = (YHBullet*)bullet;
        if (! bulletSprite->getIsActive()) { //检查子弹是否活动
            bulletSprite->destroy();
        }
        else{
            bool isCollide = bulletSprite->getCollideCrect().intersectsRect(m_winRect);
            if (!isCollide) {
                bulletSprite->removeFromParentAndCleanup(true);
            }
        }
    }
    
    
    if (m_ship && (! m_ship->getIsActive())) {
        m_ship->destroy();
        m_ship->removeFromParentAndCleanup(true);
        CCLog("remove ship");
        m_ship = NULL;
    }
}

void YHGameLayerFight::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent){
    CCTouch* touch = (CCTouch*) (pTouches->anyObject());
    m_pTouch = touch;
    CCPoint touchPoint = touch->getLocation();
    m_BeginPos = this->convertToNodeSpace(touchPoint);
}

void YHGameLayerFight::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent){
    CCTouch* touch = (CCTouch*) (pTouches->anyObject());
    if (m_pTouch != touch) {
        CCLOG("Return");
        return;
    }
    CCPoint touchPoint = touch->getLocation();
    m_EndPos = this->convertToNodeSpace(touchPoint);
    
    if (ccpDistance(m_BeginPos, m_EndPos) > 3) {
        if (m_ship) {
            CCPoint deltaPoint = ccpSub(m_EndPos, m_BeginPos);
            CCPoint curPos = m_ship->getPosition();
            CCPoint target = ccpAdd(curPos, deltaPoint);
            
            target = ccpClamp(target, CCPointZero, ccp(m_winSize.width, m_winSize.height));
            m_ship->setPosition(target);
        }
        
        m_BeginPos = m_EndPos;
    }
}

void YHGameLayerFight::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent){
    
}

void YHGameLayerFight::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent){
    
}

